import { changeContainerStatusReq, listContainerReq } from '@/api/docker'
import { debug } from '@/components/toast/debug'
import { getBehavior } from '@/components/virtual/context/behavior'
import { loading } from '@/components/virtual/tools/loading'
import { useUserStore } from '@/stores/auth'
import { useContainersStore } from '@/stores/containers'
import { message } from 'ant-design-vue'
import { forkJoin, from } from 'rxjs'
import { useI18n } from 'vue-i18n'

const useExitOperation = () => {
  const { t } = useI18n()
  const userStore = useUserStore()

  const containerStore = useContainersStore()

  /**
   * 获取容器ID 流
   */
  const getUserContainerIdsStream$ = from(
    listContainerReq({
      label: [`username=${userStore.user?.username}`],
    })
  )

  const stop = async (imageIds: string[], callBack?: () => void) => {
    loading({
      message: t('exitOperation.loading'),
    })

    const stop$ = forkJoin(
      imageIds.map((id) =>
        from(
          changeContainerStatusReq({
            id,
            sign: 'stop',
          })
        )
      )
    )

    stop$.subscribe({
      next: () => {
        message.success(t('exitOperation.stoped'), 2.5, () => {
          loading({
            message: '',
            duration: 500,
          })
          callBack && callBack()
        })
      },
      error: (e) => {
        message.error(e)
      },
    })
  }
  const terminate = async (imageIds: string[], callBack?: () => void) => {
    loading({
      message: t('exitOperation.loading'),
    })

    const delete$ = containerStore.M_deleteContainers(imageIds)
    delete$?.subscribe({
      next: () => {
        message.success(t('exitOperation.terminated'), 2.5, () => {
          loading({
            message: '',
            duration: 500,
          })
          callBack && callBack()
        })
      },
      error: (e) => {
        message.error(e)
      },
    })
  }

  //退出逻辑
  const exitFn = (behaviorType: string, callBack?: () => void) => {
    getUserContainerIdsStream$.subscribe({
      next: (data) => {
        const imageIds = (data as any[]).map((container: any) => container.Id)
        const behavior = getBehavior(behaviorType) //获取behavior
        debug(`leave behavior:${behavior}`)
        switch (behavior) {
          default:
            callBack && callBack()
            break
          case 'stop':
            callBack
              ? stop(imageIds, () => {
                  callBack()
                })
              : stop(imageIds)
            break
          case 'terminate':
            callBack
              ? terminate(imageIds, () => {
                  callBack()
                })
              : terminate(imageIds)
            break
        }
      },
    })
  }
  const exitByLeave = (callBack?: () => void) => {
    exitFn('leave', callBack)
  }
  const exitByFinish = (callBack?: () => void) => {
    exitFn('finish', callBack)
  }

  return {
    exitByLeave,
    exitByFinish,
    stop,
    terminate,
  }
}

export { useExitOperation }
